package movie.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDao {
	protected Connection conn = null;
	protected PreparedStatement stmt = null;
	protected ResultSet rs = null;
	
	//打开链接
	public void openConnection(){
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/movie","root","123456");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//关闭连接
	public void closeConnection(){
		try {
			if(rs!=null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(stmt!=null)
				stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(conn!=null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	//添加
	public int excuteUpdate(String sql,Object[] paramters) throws SQLException{
		stmt = conn.prepareStatement(sql);
		if(paramters != null){
			for(int i = 0 ; i < paramters.length; i++){
				stmt.setObject(i+1, paramters[i]);
			}
		}
		return stmt.executeUpdate();
	}
	
	//查询
	public ResultSet excuteQuery(String sql , Object[] paramters) throws SQLException{
		stmt = conn.prepareStatement(sql);
		if(paramters != null){
			for(int i = 0 ; i < paramters.length; i++){
				stmt.setObject(i+1, paramters[i]);
			}
		}
		return stmt.executeQuery();
	}
}
